package roadsuggester.main;

import java.util.ArrayList;
import java.util.List;

import com.google.android.maps.GeoPoint;

import roadsuggester.db.UserLocationsDatabase;
import roadsuggester.db.UserLocationsDatabase.UserLocation;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.location.Address;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


public class AddNewLocation extends Activity
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_new_location);

		if(getIntent().getBooleanExtra("editMode", false))
		{
			long locationID=getIntent().getLongExtra("editID", -1);
			if(locationID!=-1)
			{
				UserLocationsDatabase db=new UserLocationsDatabase(this);
				UserLocation location=db.getLocationByID(locationID);

				((TextView) findViewById(R.id.userLocationLabel)).setText(location.label);
				((TextView) findViewById(R.id.userLocationAddress)).setText(location.address);
			}
		}
	}

	public void onCancelButtonPressed(View view)
	{
		finish();
	}

	public void onSaveButtonPressed(View view)
	{
		String errorMessage="";
		boolean error=false;

		String userLocationLabel=((TextView) findViewById(R.id.userLocationLabel)).getText().toString();
		String userLocationAddress=((TextView) findViewById(R.id.userLocationAddress)).getText().toString();


		if(userLocationLabel.length()==0)
		{
			errorMessage="Please enter a valid name!";
			error=true;
		}
		if(userLocationAddress.length()==0)
		{
			errorMessage="Please enter a valid address";
			error=true;
		}

		if(error)
		{
			AlertDialog.Builder builder=new AlertDialog.Builder(this);
			builder.setMessage("Error: "+errorMessage).setCancelable(true).setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int id)
				{
					dialog.cancel();
				}
			});
			AlertDialog alert=builder.create();
			alert.show();
		}
		else
		{
			Address googleAddress=Utils.findAddress(userLocationAddress, this);
			
			
		
			if(getIntent().getBooleanExtra("editMode", false))
			{
				//Editing an already existing location
				long locationID=getIntent().getLongExtra("editID", -1);
				if(locationID!=-1)
				{
					UserLocationsDatabase db=new UserLocationsDatabase(this);
					db.updateLocation(locationID, userLocationLabel, userLocationAddress, googleAddress.getLatitude(), googleAddress.getLongitude());
				}

			}
			else
			{
				//Adding a new location
				UserLocationsDatabase db=new UserLocationsDatabase(this);
				db.addLocation(userLocationLabel, userLocationAddress, googleAddress.getLatitude(), googleAddress.getLongitude());
			}
			setResult(IntentResultCodes.UPDATE_DATABASE);
			finish();
		}
	}
}
